// src/services/request.js

// 该文件用于封装请求方法，方便在项目中调用
// 基础的请求端口，开发环境下为8081

import { BASE_URL } from '../config/networkConfig';

const request = async (endpoint, method = 'GET', body = null) => {
  const url = `${BASE_URL}${endpoint}`;
  const headers = {
    'Content-Type': 'application/json',
  };

  const token = localStorage.getItem('Authorization');
  if (token) {
    headers.Authorization = token;
  }

  const options = {
    method,
    headers,
  };

  if (body) {
    options.body = JSON.stringify(body);
  }

  console.log('url-->', url);

  const response = await fetch(url, options);
  const data = await response.json();

  console.log('data-->', data);

  if (!response.ok) {
    const error = new Error(data.message || 'An error occurred');
    error.status = response.status;
    error.data = data;
    throw error;
  }

  return data;
};

export default request;
